import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/GlobalData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/cache_mgr.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

///商品搜索
class ClassifySearchController extends BaseController {
  ///搜索关键字
  String keywords = '';

  ///高亮关键词
  List<String> highLightWords = [];

  ///搜索框控制器
  late TextEditingController textEditingController;

  ///是否显示搜索建议
  bool isShowSuggest = false;

  ///搜索建议列表
  List suggestList = [];

  ///搜索历史
  List searchHistory = [];

  ///搜索热词
  List hotList = [];

  @override
  void onInit() async {
    super.onInit();
    textEditingController = TextEditingController();
    await CacheMgr.getInstance();
    await getHotWords();
    update();
    readHistory();
  }

  ///搜索建议
  void searchSuggest(String value) async {
    keywords = value;
    highLightWords = keywords.split('');
    List data = await suggestRequest();
    suggestList = data;
    update();
  }

  ///获取搜索热词
  Future getHotWords() async {
    return Network.getHotWord().then((value) {
      hotList = value;
    });
  }

  ///建议接口
  Future suggestRequest() async {
    Map<String, dynamic> params = {};
    params['keywords'] = keywords;
    params['limit'] = 10;
    params['sid'] = AppData.sid;
    return await Network.searchSuggest(params);
  }

  ///读取搜索历史
  void readHistory() {
    searchHistory = Tools.getSearchHistory();
    update();
  }

  ///清除搜索历史
  void clearHistory() {
    Tools.showModal(
      content: '确定清除所有历史记录吗',
      onConfirm: (tag) {
        SmartDialog.dismiss();
        Tools.showToast('清除成功');
        Tools.clearSearchHistory();
        readHistory();
      },
    );
  }

  ///跳转搜索结果
  void jumpResult() {
    String value = textEditingController.value.text;
    keywords = value;
    Tools.setSearchHistory(value);
    readHistory();
    update();
    UmengCommonSdk.onEvent('搜索结果', {'keywords': keywords});
    Get.toNamed('${Routes.searchResult}/?keywords=${Uri.encodeComponent(value)}');
  }

  ///选择关键词
  void selectKeywords(String value) {
    keywords = value;
    textEditingController = TextEditingController(text: value);
    suggestList = [];
    update();
    Future.delayed(const Duration(milliseconds: 500));
    jumpResult();
  }
}
